<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * Session cache driver.
 *
 * Cache library config goes in the session.storage config entry:
 * $config['storage'] = array(
 *     'driver' => 'apc',
 *     'requests' => 10000
 * );
 * Lifetime does not need to be set as it is
 * overridden by the session expiration setting.
 *
 * $Id: cache.php 628 2009-11-09 09:19:06Z wangzh $
 *
 * @package    Core
 * @author     Ko Team, Eric
 * @copyright  (c) 2007-2008 Ko Team
 * @license    http://kophp.com/license.html
 */
class Session_Cache extends Session 
{
	/**
	 * @var Cache Object
	 */
	protected $_cache;

	public function id()
	{
		$cookie = Cookie::get('sess_id');
		if (empty($cookie))
		{
			$cookie = md5(microtime().mt_rand(100000,999999));
			Cookie::set('sess_id', $cookie, $this->_lifetime);
		}

		return $cookie;
	}

	public function __construct($config = NULL, $id = NULL)
	{
		$name = !empty($config['driver']) ? $config['driver'] : 'default';
		$this->_cache = Cache::instance($name);
		parent::__construct($config, $id);
	}

	protected function _read($id = NULL)
	{
		empty($id) && ($id = $this->id());
		$id = $this->_makeKey($id);
        if ($data = $this->_cache->get($id))
		{
            return $data;
        }
        return null;
	}

	protected function _regenerate()
	{
		$cookie = md5(microtime().mt_rand(100000,999999));
		Cookie::delete('sess_id');
		Cookie::set('sess_id', $cookie, $this->_lifetime);
		return $cookie;
	}

	protected function _write()
	{
		$id = $this->_makeKey($this->id());
		return $this->_cache->set($id, $this->__toString());
	}

	protected function _destroy()
	{
		$id = $this->_makeKey($this->id());
		return $this->_cache->delete($id);
	}

	protected function _makeKey($id)
    {
        return 'SESS_' . $id;
    }
}